package net.vsame.url2sql.domain;

import net.vsame.url2sql.helper.Url2SqlMappingHelper;
import net.vsame.url2sql.helper.WebHelper;


/**
 * url2sql子模块(每个模块以功能划分，表现为不同的jar)
 * @author <a href="mailto:gaollg@sina.com">Gaollg</a>
 * @data 2013-5-6
 */
public abstract class Url2SqlModel {
	
	/**
	 * 上下文路径
	 */
	private String contextPath = null;
	public String getContextPath() {
		return contextPath;
	}
	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}

	/**
	 * 加载顺序
	 */
	private double index;
	public double getIndex() {
		return index;
	}
	public void setIndex(double index) {
		this.index = index;
	}
	
	/**
	 * jar包名称
	 */
	private String jarName;
	public String getJarName() {
		return jarName;
	}
	public void setJarName(String jarName) {
		if(jarName == null){
			return ;
		}
		String[] array = jarName.split("-");
		try{
			if(!"url2sql".equals(array[0])){
				throw new RuntimeException();
			}
			contextPath = array[2];
			index = Double.parseDouble(array[3]);
		}catch (Exception e) {
			throw new RuntimeException("url2sql jarName mustbe 'url2sql-modelName-contextPath-loadIndex-version.jar'");
		}
		this.jarName = jarName;
	}
	
	/**
	 * true表示为Web项目
	 * @return
	 */
	public abstract boolean isWeb();
	
	/**
	 * 模块初始化调用
	 */
	public abstract void init();
	
	/**
	 * 每次请求都会调用
	 */
	public void invoke(Url2SqlModelChain chain){
		chain.next();
	}
	
	public void addUrlConfig(UrlConfig urlConfig){
		String url = urlConfig.getUrl();
		if(!url.startsWith("/")){
			url = "/" + url;
		}
		if(this.contextPath != null){
			urlConfig.setUrl("/" + this.contextPath + url);
		}
		Url2SqlMappingHelper.addUrlConfig(urlConfig);
	}
	
	public void addGlobleUrlConfig(UrlConfig urlConfig){
		Url2SqlMappingHelper.addUrlConfig(urlConfig);
	}
	
	public void addUrlConfig(String url, Class<?> clazz){
		if(!url.startsWith("/")){
			url = "/" + url;
		}
		if(this.contextPath != null){
			url = "/" + this.contextPath + url;
		}
		Url2SqlMappingHelper.addUrlConfig(url, clazz);
	}
	
	public void addGlobleUrlConfig(String url, Class<?> clazz){
		if(!url.startsWith("/")){
			url = "/" + url;
		}
		Url2SqlMappingHelper.addUrlConfig(url, clazz);
	}
	
	public void addInterceptorConfig(String regex, String js, int status){
		Url2SqlMappingHelper.addInterceptorConfig(regex, js, status);
	}
	public void addInterceptorConfig(String regex, String js){
		Url2SqlMappingHelper.addInterceptorConfig(regex, js, 1);
	}
	public Url2SqlContext getContext(){
		return WebHelper.getContext();
	}
	
}
